<!--
 * @Author: zhangyang
 * @Date: 2022-05-31 14:02:32
 * @LastEditTime: 2022-06-30 08:57:03
 * @Description: 
-->
<script lang="ts" setup>
import useFormMode from '@/hooks/useFormMode';
import { NButton, NSpace, NTag, type SelectOption } from 'naive-ui';
import type { TableDataItem, TableHeadItemPro, BaseQuery, ApiItem, RoleItem } from '@/typings';
import { addApiItem, changeApiItem, deleteApi, getApiList } from '@/api/api';
import { methodObj } from '@/conf';
import { getRoleList } from '@/api/role';

interface Form extends ApiItem {};
const FORM_TEMP: Form = {
  id: 0,
  path: '',
  desc: '',
  method: 'POST',
  category: '',
  roleIds: []
};
const {
  isAdd,
  isEdit,
  edit,
  del,
  sure,
  clear,
  form,
  formRef,
  // @ts-ignore
  validForm
} = useFormMode<Form>(FORM_TEMP, {
  // @ts-ignore
  addCbk: async () => {
    const res: boolean = await validForm();
    if (res) {
      const v = deepClone(form.value);
      clear();
      await addApiItem(v);
      window.$message.success('新增成功！');
    }
    return res;
  },
  // @ts-ignore
  modCbk: async () => {
    const res: boolean = await validForm();
    if (res) {
      const v = deepClone(form.value);
      clear();
      await changeApiItem(v);
      window.$message.success('修改成功！');
    }
    return res;
  },
  delCbk: async (row) => {
    await deleteApi(row.id.toString());
    window.$message.success('删除成功！');
    query.pageNum = 1;
  },
  cgEffect: () => getList(),
});
const renderOperate = (row: TableDataItem<Form>) => {
  return h(NSpace, {}, {
    default: () => [
      h(
        NButton,
        { type: 'info', size: 'small', ghost: true, onClick: () => edit(row) },
        { default: () => '编辑' }
      ),
      h(
        NButton,
        { type: 'error', size: 'small', ghost: true, onClick: () => del(row) },
        { default: () => '删除' }
      ),
    ]
  })
};
const tableHead: TableHeadItemPro<Form>[] = [
  { key: 'id', title: '接口ID' },
  { key: 'desc', title: '接口描述' },
  // @ts-ignore
  { key: 'method', title: '接口方法', render: (row) => h(NTag, {
      type: methodObj[row.method]
    }, {
      default: () => row.method
    })
  },
  { key: 'category', title: '接口分组' },
  { key: 'path', title: '接口路径' },
  { key: 'creator', title: '创建信息' },
  { key: 'id', title: '操作', render: renderOperate, width: '320' }
];
const tableData = ref<TableDataItem[]>([]);

type Query = BaseQuery & Partial<Form>;
const query = reactive<Query>({
  pageNum: 1,
  pageSize: 50,
  total: 0,
  path: '',
});

const roleList = ref<SelectOption[]>([]);

const getList = async () => {
  const { list: role_list } = await getRoleList({ noPagination: true });
  roleList.value = (role_list || []).map((item: RoleItem) => {
    return {
      label: item.desc,
      value: item.id
    };
  });
  
  const { list, pageNum, pageSize, total } = await getApiList(query);
  tableData.value = deepClone(list || []);
  query.pageNum = pageNum;
  query.pageSize = pageSize;
  query.total = total;
};

getList();
</script>

<route lang="yaml">
meta:
  title: 接口管理
  authPath: /system/api
</route>

<template>
  <div class="flex">
    <div class="m-2">
      <NInput v-model:value="query.path" placeholder="请输入接口路径" />
    </div>
    <div class="m-2">
      <NButton type="info" ghost @click="getList">查询</NButton>
    </div>
    <div class="m-2">
      <NButton type="success" ghost @click="isAdd=true">添加</NButton>
    </div>
  </div>
  <div class="m-2">
    <YoungTablePro
      v-model:page="query.pageNum"
      v-model:limit="query.pageSize"
      :total="query.total"
      :table-data="tableData"
      :table-head="tableHead"
      @page-change="getList"
    />
  </div>
  <YoungDialog
    :is-add="isAdd"
    :is-edit="isEdit"
    @sure="sure"
    @clear="clear"
  >
    <template #body>
      <NForm
        ref="formRef"
        :model="form"
        label-placement="left"
        label-width="100"
      >
        <NFormItem
          label="分组名称"
          path="category"
          :rule="[{ required: true, message: '请填写分组名称', trigger: 'blur' }]"
        >
          <NInput v-model:value="form.category" @change="form.path = `/${form.category}/`" />
        </NFormItem>
        <NFormItem
          label="接口描述"
          path="desc"
          :rule="[{ required: true, message: '请填写接口描述', trigger: 'blur' }]"
        >
          <NInput v-model:value="form.desc" />
        </NFormItem>
        <NFormItem
          label="请求方法"
        >
          <NSelect
            v-model:value="form.method"
            :options="Object.keys(methodObj).map((v) => {
              return {
                label: v,
                value: v
              };
            })"
          />
        </NFormItem>
        <NFormItem
          label="接口路径"
          path="path"
          :rule="[{ required: true, message: '请填写接口路径', trigger: 'blur' }]"
        >
          <NInput v-model:value="form.path" />
        </NFormItem>
        <NFormItem
          label="关联角色"
        >
          <NSelect v-model:value="form.roleIds" multiple :options="roleList" />
        </NFormItem>
      </NForm>
    </template>
  </YoungDialog>
</template>